package cn.springboot.erp.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.springboot.erp.commons.QueryParams;
import cn.springboot.erp.commons.ResponseResult;
import cn.springboot.erp.entity.Shipments;
import cn.springboot.erp.service.ShipmentsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("shipment")
@Api(tags = "发货管理")
public class ShipmentController {

    @Resource
    private ShipmentsService shipmentsService;

    @ApiOperation("数据分页")
    @PostMapping("page")
    public ResponseResult listPage(@RequestBody QueryParams<Shipments> queryParams){
        return shipmentsService.listPage(queryParams);
    }

    @ApiOperation("根据id查询")
    @GetMapping("selectById/{id}")
    public ResponseResult selectById(@PathVariable("id") Integer id){
        Shipments shipments = shipmentsService.getById(id);
        return ResponseResult.Success().data("one",shipments);
    }

    @ApiOperation("根据id删除")
    @GetMapping("deleteById/{id}")
    public ResponseResult deleteById(@PathVariable("id") Integer id){
        return shipmentsService.deleteById(id);
    }

    @ApiOperation("修改状态")
    @GetMapping("state/{id}/{state}")
    public ResponseResult state(@PathVariable("id") Integer id,@PathVariable("state") Integer state){
        Shipments shipments = new Shipments();
        shipments.setId(id);
        shipments.setStatus(state);
        shipmentsService.updateById(shipments);
        return ResponseResult.Success().msg("状态修改完成");
    }

    @ApiOperation("添加或编辑")
    @PostMapping("insertOrUpdate")
    public ResponseResult insertOrUpdate(@RequestBody Shipments shipments){
        Integer orderId = shipments.getOrderId();
        LambdaQueryWrapper<Shipments> lambda = new QueryWrapper<Shipments>().lambda();
        lambda.eq(Shipments::getOrderId,orderId);
        Shipments one = shipmentsService.getOne(lambda);
        if (ObjectUtils.isNotNull(one)){
            if (ObjectUtil.equal(one.getId(),shipments.getId())){
                shipmentsService.saveOrUpdate(shipments);
                return ResponseResult.Success().msg("修改成功");
            }
            return ResponseResult.Fail().msg("订单编号已经存在");
        }
        shipments.setShipmentDate(new Date());
        shipmentsService.saveOrUpdate(shipments);
        return ResponseResult.Success().msg("添加成功");
    }
}
